package com.learning.regex;

/**
 * Created by xieyichao on 2017/5/13.
 */

public class Matcher {

    Pattern mPattern;
    CharSequence mRegular;
    CharSequence mMatcherStr;
    int mStrPos;

    public Matcher(Pattern pattern) {
        mPattern = pattern;
    }

    public boolean matches(){

        mRegular = mPattern.getRegular();
        mMatcherStr = mPattern.getMatcherStr();

        mStrPos = 0;

        for(int i=0;i<mRegular.length();i++){

            switch (mRegular.charAt(i)){
                case '+':   //{1,}
                    if(!plus(mStrPos)){
                        return false;
                    }
                    break;
                case '*':   //{0,}
                    asterisk();
                    break;
                case '?':   //{0,1}
                    if(!question()){
                        return false;
                    }
                    break;
                default:
                    if(mRegular.charAt(i) == mMatcherStr.charAt(mStrPos)){
                        if(mMatcherStr.length() -1 != mStrPos){
                            mStrPos++;
                        }
                    }else{
                        return false;
                    }
                    break;
            }
        }

        return true;
    }

    private boolean plus(int startPos){
        if(mMatcherStr.charAt(startPos) != mMatcherStr.charAt(startPos-1)){
            return false;
        }else{
            if(mMatcherStr.charAt(mStrPos) != mMatcherStr.charAt(mStrPos-1)){
                return true;
            }
        }
        if(mMatcherStr.length()-1 != mStrPos){
            mStrPos++;
            plus(startPos);
        }
        return true;
    }

    private boolean question(){
        for(int i=0;i<=1;i++){
            if(mMatcherStr.charAt(mStrPos) != mMatcherStr.charAt(mStrPos-1)){
                return true;
            }
            if(mMatcherStr.length()-1 != mStrPos){
                mStrPos++;
            }else{
                if(i == 0){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean asterisk(){
        if(mMatcherStr.charAt(mStrPos) != mMatcherStr.charAt(mStrPos-1)){
            return true;
        }
        if(mMatcherStr.length()-1 != mStrPos){
            mStrPos++;
            asterisk();
        }
        return true;
    }

}
